package com.campus.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.campus.app.mapper.CloudFileMapper;
import com.campus.app.mapper.CheckClassMapper;
import com.campus.app.service.CheckClasssService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.commons.entity.CheckClass;
import com.campus.commons.utils.Error;
import com.campus.commons.utils.Result;
import com.campus.commons.utils.Tool;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 查班表 服务实现类
 * </p>
 *
 * @author Rin
 * @since 2020-12-24
 */
@Service
public class CheckClassServiceImpl extends ServiceImpl<CheckClassMapper, CheckClass> implements CheckClasssService {
    @Autowired
    private CheckClassMapper checkClassMapper;
    @Autowired
    private CloudFileMapper fileMapper;

    @Override
    public Result<List<CheckClass>> getCheckClass(int size, int limit) {
        Page<CheckClass> checkClassPage = checkClassMapper.selectPage(new Page<CheckClass>(size, limit), null);
        return Result.result(checkClassPage);
    }

    @Override
    public Result<List<CheckClass>> getCheckClassByRed(Integer work, int page, int limit) {
        QueryWrapper<CheckClass> queryWrapper = new QueryWrapper<>();
        queryWrapper.le("work", work);
        return Result.result(checkClassMapper.selectPage(new Page<CheckClass>(page, limit), queryWrapper));
    }

    @Override
    public Result<List<CheckClass>> getCheckClassByDate(String start, String end, int size, int limit, String className, @Min(1) @Max(100) int formalWork) {
        QueryWrapper<CheckClass> wrapper = new QueryWrapper<>();


        if (StringUtils.isEmpty(end) && !StringUtils.isEmpty(start)) {
            wrapper.ge("date", start);
        }
        if (!StringUtils.isEmpty(end) &&StringUtils.isEmpty(start)) {
            wrapper.ge("date", end);
        }
        if (StringUtils.isEmpty(end) && StringUtils.isEmpty(start)) {
            return getCheckClass(size,limit );
        }
        if (!StringUtils.isEmpty(start) && !StringUtils.isEmpty(end)) {
            wrapper.between("date", start, end);
        }
        if (!StringUtils.isEmpty(className)) {
            wrapper.inSql("classId", "select id from class where className='" + className+"'");
        }
        if (formalWork >= 0) {
            wrapper.lt("formalWork", formalWork);
        }
        wrapper.orderByDesc("date");
        return Result.result(checkClassMapper.selectPage(new Page<CheckClass>(size,limit), wrapper));
    }

    @Override
    public Result del(Integer id) {

        return Result.success("删除成功",checkClassMapper.deleteById(id));
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Result upDate(@NotNull CheckClass checkClass) {
        new FunctionServerImpl().init();
        checkClass.setStudentid(FunctionServerImpl.students.get(checkClass.getStudentName()));
        QueryWrapper<CheckClass> wrapper = new QueryWrapper<>();
        wrapper.inSql("classRoomId", "SELECT id FROM class_room WHERE roomName='" + checkClass.getClassRoomName() + "'");
        wrapper.inSql("classId", "SELECT id FROM class WHERE className ='" + checkClass.getClassName() + "'");
//        wrapper.inSql("studentId", "SELECT id FROM student WHERE stuName='" + checkClass.getStudentName() + "'");存在小bug(埋坑)
        return Result.success(checkClassMapper.updateById(checkClass));
    }

    @Override
    public Result addCheckClassMap(@NotNull CheckClass checkClass) {
        if (checkClass.getIstop() <= 0&&StringUtils.isEmpty(checkClass.getClassRoomName())) {
            return Result.error(Error.Map_E3R, null);
        }
        HashMap<String, CheckClass> map = new HashMap<>();
        map.put(checkClass.getClassRoomName(), checkClass);
        checkClassMap.put(checkClass.getIstop(), map);
        return Result.result(1);
    }

    @Override
    public Result getCacheMap() {
        return Result.success(checkClassMap.values());
    }

    @Override
    public Result upCheckClassMap(@NotNull CheckClass checkClass) {
        addCheckClassMap(checkClass);
        return Result.result(1);
    }
    @Async
    @Override
    public void exportExcelForClass() {
        if (checkClassMap.size()<1) {
            throw new RuntimeException("数据有误，无法执行导出表格");
        }
        Map<String, CheckClass> sCheckClassMap = checkClassMap.get(1);
        Map<String, CheckClass> xCheckClassMap = checkClassMap.get(2);
        String[] floors = {"一楼", "二楼", "三楼"};
        //循环生成三次表格； 截取教室；
        for (int i = 1; i <= 3; i++) {
            HashMap<String, Object> data = new HashMap<>();
            String floor=i+"";
            List<CheckClass> sList = sCheckClassMap.values().stream().filter(c -> c.getClassRoomName().substring(1, 2).equals(floor)).collect(Collectors.toList());
            List<CheckClass> xList = xCheckClassMap.values().stream().filter(c -> c.getClassRoomName().substring(1, 2).equals(floor)).collect(Collectors.toList());
            data.put("date", Tool.getDateToString(null));
            data.put("studentName",sList.get(0).getStudentName());
            data.put("s", sList);
            data.put("x", xList);
            fileMapper.addFile(Tool.exportExcel("查班模板.xlsx",  floors[(i-1)]+"查班记录.xlsx",data,2));
            checkClassMap.clear();
        }
    }

    @Override
    public Result<CheckClass> getacheckclassrecord(@Min(1) int id) {
        QueryWrapper<CheckClass> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        return Result.success(checkClassMapper.selectOne(wrapper));
    }

    @Override
    public Result delCheckClassMap(@NotNull String classRoomName) {
        if (StringUtils.isEmpty(classRoomName)) {
            return Result.error(Error.Map_E3R, null);
        }
        checkClassMap.remove(classRoomName);
        return Result.result(1);
    }

}
